﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using PhoneFilter.Helper;
using System.IO;
using System.Collections;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;

namespace PhoneFilter
{
    [ComVisible(true), PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public partial class Form1 : Form, IWebInvoke
    {
        private string curIMEI;
        private string curPhone;
        private string defaultUrl;
        private bool running;
        private int serviceType;
        private string urlBookProductResult;
        private string urlMain;
        private string urlProductOrder;
        private string urlRegImei;
        private string urlRegUrl;

        public Form1()
        {
            InitializeComponent();
            this.running = false;
            this.urlProductOrder = "incrementProBookInitAction.action";
            this.urlRegImei = "";
            this.defaultUrl = "https://211.138.30.200/WSKF/";
            this.serviceType = 0;
            this.urlRegUrl = "termSaleInitAction.action";
            this.urlMain = "mainAction.action";
            this.urlBookProductResult = "bookIncPro.action";
            this.curPhone = "";
            this.curIMEI = "";
        }

        public Form1(string _defUrl)
        {
            InitializeComponent();
            this.running = false;
            this.urlProductOrder = "incrementProBookInitAction.action";
            this.urlRegImei = "";
            this.serviceType = 0;
            this.urlRegUrl = "termSaleInitAction.action";
            this.urlMain = "mainAction.action";
            this.urlBookProductResult = "bookIncPro.action";
            this.curPhone = "";
            this.curIMEI = "";
            this.defaultUrl = _defUrl;
        }

        private void AppendTxt(string str)
        {
            if (this.richTextBox1.Lines.Length > 0x7d0)
            {
                this.richTextBox1.Clear();
            }
            str = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":>>" + str + "\r\n";
            this.richTextBox1.AppendText(str);
            this.richTextBox1.ScrollToCaret();
            Log.PrintLog(str);
        }

        private void BindCombobox()
        {
            this.cbbCommonService.DataSource = this.InitData();
            this.cbbCommonService.DisplayMember = "text";
            this.cbbCommonService.ValueMember = "value";
            this.cbbCommonService.SelectedIndex = this.cbbCommonService.Items.Count - 1;
        }

        private void btn086Finish_Click(object sender, EventArgs e)
        {
            if (this.running && (this.serviceType == -1))
            {
                this.running = false;
                this.tProduct.Stop();
            }
        }

        private void btn86Start_Click(object sender, EventArgs e)
        {
            if (this.running)
            {
                MessageBox.Show("程序已经在运行中");
            }
            else
            {
                this.serviceType = -1;
                this.Main086();
                this.running = true;
            }
        }

        private void btnFinish_Click(object sender, EventArgs e)
        {
            this.readDBTimer.Stop();
        }

        private void btnFinish_Click_1(object sender, EventArgs e)
        {
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                FileStream stream = null;
                StreamReader reader = null;
                try
                {
                    string str;
                    SqliteManager.ExecuteNonQuery("delete from phonelist");
                    stream = new FileStream(this.openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
                    reader = new StreamReader(stream, Encoding.Default);
                    Hashtable hashtable = new Hashtable();
                    ArrayList list = new ArrayList();
                    while ((str = reader.ReadLine()) != null)
                    {
                        list.Add(str.Trim());
                    }
                    SqliteManager.ImportPhone(list);
                    MessageBox.Show("共导入" + list.Count + "条数据");
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
                finally
                {
                    reader.Close();
                    stream.Close();
                    reader = null;
                    stream = null;
                }
            }
        }

        private void btnImportJS_Click(object sender, EventArgs e)
        {
            string[] strArray = new string[] { "tool.js" };
            foreach (string str in strArray)
            {
                string filePath = string.Format(@"{0}\Scripts\{1}", Environment.CurrentDirectory, str);
                HtmlElement newElement = WebBrowserHelper.LoadAndCreateLocationJS(WebBrowserHelper.getDocFromWebBrowser(this.wbMain, this.urlProductOrder), filePath);
                if (newElement != null)
                {
                    this.AppendTxt(string.Format("成功加载本地文件:{0}", str));
                    WebBrowserHelper.getDocFromWebBrowser(this.wbMain, this.urlProductOrder).Body.AppendChild(newElement);
                }
            }
        }

        private void btnMainFinish_Click(object sender, EventArgs e)
        {
            if (this.running && (this.serviceType != -1))
            {
                this.running = false;
                this.tCommon.Stop();
            }
        }

        private void btnMainStart_Click(object sender, EventArgs e)
        {
            if (this.running)
            {
                MessageBox.Show("程序已经在运行中");
            }
            else
            {
                this.running = true;
                this.serviceType = this.cbType.SelectedIndex;
                this.MainCommon();
            }
        }

        private void btnOutput_Click(object sender, EventArgs e)
        {
            DataSet set = SqliteManager.ExecuteDataSet("select * from phonelist order by rowid");
            StringBuilder builder = new StringBuilder();
            if ((set != null) && (set.Tables[0].Rows.Count > 0))
            {
                for (int i = 0; i < set.Tables[0].Rows.Count; i++)
                {
                    DataRow row = set.Tables[0].Rows[i];
                    builder.Append(row["phone"].ToString() + "\t" + row["state"].ToString() + "\r\n");
                }
            }
            if (builder.Length > 0)
            {
                string path = "";
                if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    path = this.saveFileDialog1.FileName;
                }
                StreamWriter writer = new StreamWriter(path);
                writer.Write(builder.ToString());
                writer.Close();
            }
            else
            {
                MessageBox.Show("没有能够导出的数据");
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            HtmlDocument document = WebBrowserHelper.getDocFromWebBrowser(this.wbMain, this.urlProductOrder);
            if (document != null)
            {
                object[] args = new object[] { "15838330528" };
                document.InvokeScript("b", args);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                FileStream stream = null;
                StreamReader reader = null;
                try
                {
                    string str;
                    SqliteManager.ExecuteNonQuery("delete from phone086");
                    stream = new FileStream(this.openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
                    reader = new StreamReader(stream, Encoding.Default);
                    Hashtable hashtable = new Hashtable();
                    ArrayList list = new ArrayList();
                    while ((str = reader.ReadLine()) != null)
                    {
                        str = str.Trim();
                        string[] strArray = str.Split(new char[] { ' ' });
                        if (strArray.Length != 2)
                        {
                            strArray = str.Split(new char[] { ',' });
                        }
                        if (strArray.Length != 2)
                        {
                            strArray = str.Split(new char[] { '\t' });
                        }
                        if (strArray.Length != 2)
                        {
                            MessageBox.Show("导入格式不正确，请重新选择");
                            return;
                        }
                        list.Add(strArray);
                    }
                    SqliteManager.ImportPhone086(list);
                    MessageBox.Show("共导入" + list.Count + "条数据");
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
                finally
                {
                    reader.Close();
                    stream.Close();
                    reader = null;
                    stream = null;
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DataSet set = SqliteManager.ExecuteDataSet("select * from phone086 order by rowid");
            StringBuilder builder = new StringBuilder();
            if ((set != null) && (set.Tables[0].Rows.Count > 0))
            {
                for (int i = 0; i < set.Tables[0].Rows.Count; i++)
                {
                    DataRow row = set.Tables[0].Rows[i];
                    string str = row["phone"].ToString();
                    string str2 = row["regstate"].ToString();
                    string str3 = row["regreason"].ToString();
                    string str4 = row["blstate"].ToString();
                    string str5 = row["reason"].ToString();
                    builder.Append(str + "\t" + str2 + "\t" + str3 + "\t" + str4 + "\t" + str5 + "\r\n");
                }
            }
            if (builder.Length > 0)
            {
                string path = "";
                if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    path = this.saveFileDialog1.FileName;
                }
                StreamWriter writer = new StreamWriter(path);
                writer.Write(builder.ToString());
                writer.Close();
            }
            else
            {
                MessageBox.Show("没有能够导出的数据");
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                FileStream stream = null;
                StreamReader reader = null;
                try
                {
                    string str;
                    SqliteManager.ExecuteNonQuery("delete from phonecommon");
                    stream = new FileStream(this.openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
                    reader = new StreamReader(stream, Encoding.Default);
                    Hashtable hashtable = new Hashtable();
                    ArrayList list = new ArrayList();
                    while ((str = reader.ReadLine()) != null)
                    {
                        str = str.Trim();
                        list.Add(str);
                    }
                    SqliteManager.ImportPhoneCommon(list);
                    MessageBox.Show("共导入" + list.Count + "条数据");
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
                finally
                {
                    reader.Close();
                    stream.Close();
                    reader = null;
                    stream = null;
                }
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            DataSet set = SqliteManager.ExecuteDataSet("select * from phonecommon order by rowid");
            StringBuilder builder = new StringBuilder();
            if ((set != null) && (set.Tables[0].Rows.Count > 0))
            {
                for (int i = 0; i < set.Tables[0].Rows.Count; i++)
                {
                    DataRow row = set.Tables[0].Rows[i];
                    string str = row["phone"].ToString();
                    string str2 = row["blstate"].ToString();
                    string str3 = row["reason"].ToString();
                    string str4 = row["cityname"].ToString();
                    string str5 = row["userinfo"].ToString();
                    builder.Append(str + "\t" + str2 + "\t" + str3 + "\t" + str4 + "\t" + str5 + "\r\n");
                }
            }
            if (builder.Length > 0)
            {
                string path = "";
                if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    path = this.saveFileDialog1.FileName;
                }
                StreamWriter writer = new StreamWriter(path);
                writer.Write(builder.ToString());
                writer.Close();
            }
            else
            {
                MessageBox.Show("没有能够导出的数据");
            }
        }

        private void EnterProductUrl()
        {
            this.AppendTxt("准备 进入 产品订购 页面");
            HtmlDocument doc = WebBrowserHelper.getDocFromWebBrowser(this.wbMain, this.urlMain);
            if (doc != null)
            {
                HtmlElement element = WebBrowserHelper.GetElementByKeyWord(doc, "span", "产品订购");
                if (element != null)
                {
                    element.Parent.InvokeMember("onclick");
                }
                else
                {
                    this.AppendTxt("没有找到 产品订购 菜单");
                }
            }
            else
            {
                this.AppendTxt("没有找到对应的页面," + this.urlMain);
            }
        }

        private void EnterRegUrl()
        {
            this.AppendTxt("打开 注册IMEI 页面");
            HtmlDocument doc = WebBrowserHelper.getDocFromWebBrowser(this.wbMain, this.urlMain);
            if (doc != null)
            {
                HtmlElement element = WebBrowserHelper.GetElementByKeyWord(doc, "span", "系统外销售4G手机转化营销活动登记");
                if (element != null)
                {
                    element.Parent.InvokeMember("onclick");
                }
                else
                {
                    this.AppendTxt("没有找到IMEI注册菜单");
                }
            }
            else
            {
                this.AppendTxt("主页面js 调用错误， 调用名称: menuNodeClick");
            }
        }

        private void ExcuteQueryInfo()
        {
            Random random = new Random();
            this.Sleep(random.Next(0x3e8, 0x7d0));
            this.AppendTxt(" 准备调用本地js 函数 d ");
            HtmlDocument document = WebBrowserHelper.getDocFromWebBrowser(this.wbMain, this.urlProductOrder);
            if (document != null)
            {
                object[] args = new object[] { this.curPhone };
                document.InvokeScript("d", args);
            }
            else
            {
                this.AppendTxt("没有找到对应的页面," + this.urlMain);
            }
        }

        private bool exec()
        {
            if (!this.running)
            {
                return false;
            }
            bool flag = false;
            DataSet set = SqliteManager.ExecuteDataSet(string.Format("select * from phonelist where state='{0}' limit 1 offset 0", SqliteManager.NOTBEGIN));
            if ((set != null) && (set.Tables[0].Rows.Count > 0))
            {
                for (int i = 0; i < set.Tables[0].Rows.Count; i++)
                {
                    DataRow row = set.Tables[0].Rows[i];
                    string phone = row["phone"].ToString();
                    this.QueryState(phone);
                    SqliteManager.ExecuteNonQuery(string.Format("update phonelist set state='{0}' where phone='{1}'", SqliteManager.QUERYING, phone));
                    flag = true;
                }
            }
            if (!flag)
            {
                MessageBox.Show("任务完成");
            }
            return flag;
        }

        private void FilterPhone(string msg)
        {
            //更新号码归属地及 用户信息
            UpdateLocalInfo(msg);

            JObject obj2 = JObject.Parse(msg);
            string str2 = obj2["marketingInfo"].ToString().Substring(3, 11);
            if (msg.Contains("errorMsg"))
            {
                this.AppendTxt("捕获到服务器获取数据异常,等待5分钟后再执行");
                SqliteManager.ExecuteNonQuery(string.Format("update phonecommon set blstate='{0}' where phone='{1}'", SqliteManager.NOTBEGIN, str2));
                this.Sleep(0x493e0);
            }
            else
            {
                string str4 = this.cbbCommonService.SelectedValue.ToString();
                JArray array = (JArray)obj2["favMap"][str4];
                string str5 = array[3].ToString();
                string str = string.Format("号码：{0}，状态:{1}", str2, str5);
                this.AppendTxt(str);
                string dISABLED = SqliteManager.DISABLED;
                if (str5 == "1")
                {
                    dISABLED = SqliteManager.ABLED;
                }
                SqliteManager.ExecuteNonQuery(string.Format("update phonecommon set blstate='{0}' where phone='{1}'", dISABLED, str2));
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.cbType.SelectedIndex = 0;
            this.cbbStartHour.SelectedIndex = 0;
            this.cbbEndHour.SelectedIndex = 0x17;
            this.wbMain.Height = (int)(((double)base.Height) / 0.8);
            this.wbMain.ScriptErrorsSuppressed = true;
            this.wbMain.ObjectForScripting = this;
            this.BindCombobox();
            SqliteManager.CheckDb();
        }

        private string GetNeedProcCommonInfo()
        {
            string str = null;
            DataSet set = SqliteManager.ExecuteDataSet(string.Format("select * from phonecommon where blstate='{0}' limit 1 offset 0", SqliteManager.NOTBEGIN));
            if ((set != null) && (set.Tables[0].Rows.Count > 0))
            {
                for (int i = 0; i < set.Tables[0].Rows.Count; i++)
                {
                    DataRow row = set.Tables[0].Rows[i];
                    str = row["phone"].ToString();
                    SqliteManager.ExecuteNonQuery(string.Format("update phonecommon set blstate='{0}' where phone='{1}'", SqliteManager.QUERYING, str));
                }
            }
            return str;
        }

        private string[] GetNeedProcIMEIInfo()
        {
            string[] strArray = null;
            bool flag = false;
            DataSet set = SqliteManager.ExecuteDataSet(string.Format("select * from phone086 where regstate='{0}' limit 1 offset 0", SqliteManager.NOTBEGIN));
            if ((set != null) && (set.Tables[0].Rows.Count > 0))
            {
                for (int i = 0; i < set.Tables[0].Rows.Count; i++)
                {
                    DataRow row = set.Tables[0].Rows[i];
                    string str = row["phone"].ToString();
                    string str2 = row["imei"].ToString();
                    strArray = new string[] { str, str2 };
                    SqliteManager.ExecuteNonQuery(string.Format("update phone086 set regstate='{0}' where phone='{1}'", SqliteManager.QUERYING, str));
                    flag = true;
                }
            }
            return strArray;
        }

        public void HtmlToForm(int type, string msg)
        {
            this.AppendTxt(string.Format("开始解析，内容：{0}, 类型：{1}", msg, type));
            switch (type)
            {
                case 1:
                    this.FilterPhone(msg);
                    break;

                case 2:
                    this.ProcIMEIInfo(msg);
                    break;

                case 3:
                    this.ProcQueryInfo(msg);
                    break;
            }
        }

        private DataTable InitData()
        {
            DataTable table = new DataTable();
            table.Columns.Add("text");
            table.Columns.Add("value");
            try
            {
                string html = HttpUtils.DoGet("http://171.8.225.192:17008/type.txt");
                JArray list = JArray.Parse(html);
                for (int i = 0; i < list.Count; i++)
                {
                    JObject obj = (JObject)list[i];
                    CreateRow(table, obj["text"].ToString(), obj["value"].ToString());
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("类型更新失败，使用默认数据");
                DataRow row = table.NewRow();
                row["text"] = "流量包升级，你用我就返-0升30";
                row["value"] = "420002883361";
                DataRow row2 = table.NewRow();
                row2["text"] = "流量包升级，你用我就返-30升40";
                row2["value"] = "420002883377";
                DataRow row3 = table.NewRow();
                row3["text"] = "2016年一季度4G套餐体验-赠送通话时长-38元及以上档";
                row3["value"] = "420002846961";
                DataRow row4 = table.NewRow();
                row4["text"] = "2016年一季度4G套餐体验-赠送通话时长-9-28元档";
                row4["value"] = "420002846963";
                DataRow row5 = table.NewRow();
                row5["text"] = "郑州流量包合约送话费和流量活动0升30";
                row5["value"] = "600000006189";
                table.Rows.Add(row);
                table.Rows.Add(row2);
                table.Rows.Add(row3);
                table.Rows.Add(row4);
                table.Rows.Add(row5);
                CreateRow(table, "全民上网", "600000019929");
                CreateRow(table, "4G套餐升级", "600000020011");
                CreateRow(table, "4G套餐体验", "600000020019");
            }
            
            
            return table;
        }

        private void CreateRow(DataTable dt, string text, string value)
        {
            DataRow row = dt.NewRow();
            row["text"] = text;
            row["value"] = value;
            dt.Rows.Add(row);
        }

        private bool is4G(string message)
        {
            this.AppendTxt("首先判断是否4G卡");
            string str = message;
            str = str.Replace(" ", "").Replace("&nbsp;", "");
            string str2 = "";
            string str3 = "是否4G卡";
            int index = str.IndexOf(str3);
            if (index > 0)
            {
                str2 = str.Substring(index + str3.Length, 6);
            }
            if (str2.Contains("否"))
            {
                return false;
            }
            return true;
        }

        private void LoadLocalJS(string url)
        {
            string[] strArray = new string[] { "tool.js" };
            foreach (string str in strArray)
            {
                string filePath = string.Format(@"{0}\Scripts\{1}", Environment.CurrentDirectory, str);
                HtmlElement newElement = WebBrowserHelper.LoadAndCreateLocationJS(WebBrowserHelper.getDocFromWebBrowser(this.wbMain, url), filePath);
                if (newElement != null)
                {
                    this.AppendTxt(string.Format("成功加载文件:{0}", str));
                    WebBrowserHelper.getDocFromWebBrowser(this.wbMain, url).Body.AppendChild(newElement);
                }
            }
        }

        private void Main086()
        {
            int num = Convert.ToInt32(this.cbbStartHour.SelectedItem);
            int num2 = Convert.ToInt32(this.cbbEndHour.SelectedItem);
            int hour = DateTime.Now.Hour;
            if ((hour >= num) && (hour <= num2))
            {
                string[] needProcIMEIInfo = this.GetNeedProcIMEIInfo();
                if (needProcIMEIInfo == null)
                {
                    this.AppendTxt("没有可以执行的任务");
                }
                else
                {
                    this.curPhone = needProcIMEIInfo[0];
                    this.curIMEI = needProcIMEIInfo[1];
                    this.EnterRegUrl();
                }
            }
            else
            {
                int minValue = Convert.ToInt32(this.tbStart.Text.Trim());
                int maxValue = Convert.ToInt32(this.tbEnd.Text.Trim());
                int num6 = new Random().Next(minValue, maxValue);
                this.AppendTxt(string.Format("没有在运行时间内， 等待5分后继续执行", new object[0]));
                this.tProduct.Interval = 0x493e0;
                this.tProduct.Start();
            }
        }

        private void MainCommon()
        {
            int num = Convert.ToInt32(this.cbbStartHour.SelectedItem);
            int num2 = Convert.ToInt32(this.cbbEndHour.SelectedItem);
            int hour = DateTime.Now.Hour;
            if ((hour >= num) && (hour <= num2))
            {
                string needProcCommonInfo = this.GetNeedProcCommonInfo();
                if (needProcCommonInfo == null)
                {
                    this.AppendTxt("没有可以执行的任务");
                    this.running = false;
                }
                else
                {
                    this.curPhone = needProcCommonInfo;
                    if (WebBrowserHelper.getDocFromWebBrowser(this.wbMain, this.urlProductOrder) == null)
                    {
                        this.EnterProductUrl();
                    }
                    else
                    {
                        this.LoadLocalJS(this.urlProductOrder);
                        this.ExcuteQueryInfo();
                    }
                }
            }
            else
            {
                this.AppendTxt(string.Format("没有在运行时间内， 等待5分后继续执行", new object[0]));
                this.tCommon.Interval = 0x493e0;
                this.tCommon.Start();
            }
        }

        private void UpdateLocalInfo(string msg)
        {
            try
            {
                JObject obj = JObject.Parse(msg);
                string cityName = obj["cityName"].ToString();
                string userInfo = obj["userInfo"].ToString();
                string sql = string.Format("update phonecommon set cityname='{0}', userinfo='{1}' where phone='{2}'", cityName, userInfo, this.curPhone);
                SqliteManager.ExecuteNonQuery(sql);
            }
            catch (Exception ex)
            {
                this.AppendTxt(GetExceptionInfo(ex));
            }
        }

        private string GetExceptionInfo(Exception exc)
        {
            string msg = string.Format("source:{0},StackTrace:{1}, Message:{2}", exc.Source, exc.StackTrace,exc.Message);
            return msg;
        }

        private void ProcBookProInfo()
        {
            this.AppendTxt(" 准备获取网页内容进行数据分析 ");
            HtmlDocument document = WebBrowserHelper.getDocFromWebBrowser(this.wbMain, this.urlBookProductResult);
            if (document != null)
            {
                string sUCCESS = "";
                string str2 = "";
                string outerHtml = document.GetElementsByTagName("html")[0].OuterHtml;
                Match match = new Regex("var\\s+message\\s+=\\s+\"(.*?)\"\\s*;", RegexOptions.IgnoreCase).Match(outerHtml);
                string str4 = match.Groups[1].Value;
                if (match.Success)
                {
                    if (str4 == "0000")
                    {
                        sUCCESS = SqliteManager.SUCCESS;
                    }
                    else
                    {
                        sUCCESS = SqliteManager.FAIL;
                        str2 = str4;
                    }
                }
                else
                {
                    sUCCESS = SqliteManager.QITA;
                    str2 = outerHtml.Substring(0, 500);
                }
                this.AppendTxt(string.Format(" 办理结果为：{0}， 原因为：{1} ", sUCCESS, str2));
                string sql = "";
                if (this.serviceType == -1)
                {
                    sql = string.Format("update phone086 set blstate='{0}', reason='{1}' where phone='{2}'", sUCCESS, str2, this.curPhone);
                }
                else if (this.serviceType == 1)
                {
                    sql = string.Format("update phonecommon set blstate='{0}', reason='{1}' where phone='{2}'", sUCCESS, str2, this.curPhone);
                }
                SqliteManager.ExecuteNonQuery(sql);
            }
            else
            {
                this.AppendTxt(" 没有找到对应网页所属的控件 ");
            }
            this.ReayNext();
        }

        private void ProcIMEIInfo(string msg)
        {
            string sUCCESS = "";
            string str2 = "";
            bool flag = false;
            if (msg.Contains("成功"))
            {
                sUCCESS = SqliteManager.SUCCESS;
                flag = true;
            }
            else
            {
                sUCCESS = SqliteManager.FAIL;
                str2 = msg;
            }
            this.AppendTxt(string.Format("准备更新注册状态为：{0}， 原因：{1}", sUCCESS, str2));
            SqliteManager.ExecuteNonQuery(string.Format("update phone086 set regstate='{0}', regreason='{1}' where phone='{2}'", sUCCESS, str2, this.curPhone));
            this.AppendTxt("注册状态更新成功");
            if (msg.Contains("成功"))
            {
                this.EnterProductUrl();
            }
            else
            {
                this.Main086();
            }
        }

        private void ProcQueryInfo(string msg)
        {
            Random random = new Random();
            if (!this.is4G(msg))
            {
                this.AppendTxt("当前卡为非4G卡,更新本地数据库");
                if (this.serviceType == -1)
                {
                    SqliteManager.ExecuteNonQuery(string.Format("update phone086 set blstate='{0}', reason='{1}' where phone='{2}'", SqliteManager.FAIL, SqliteManager.NOT4G, this.curPhone));
                }
                else
                {
                    
                    SqliteManager.ExecuteNonQuery(string.Format("update phonecommon set blstate='{0}', reason='{1}' where phone='{2}' ", SqliteManager.FAIL, "非4G卡", this.curPhone));
                }
                this.ReayNext();
            }
            else if (this.serviceType == 0)
            {
                this.FilterPhone(msg);
                this.ReayNext();
            }
            else
            {
                this.Sleep(random.Next(500, 0x3e8));
                this.AppendTxt(" 准备调用页面地js 函数 bookIncrementProduct ");
                HtmlDocument document = WebBrowserHelper.getDocFromWebBrowser(this.wbMain, this.urlProductOrder);
                if (document != null)
                {
                    document.GetElementById("mobileNo").SetAttribute("value", this.curPhone);
                    document.GetElementById("mobileNoHidden").SetAttribute("value", this.curPhone);
                    object[] args = new object[1];
                    if (this.serviceType == -1)
                    {
                        args[0] = "420002198307";
                    }
                    else
                    {
                        args[0] = this.cbbCommonService.SelectedValue;
                    }
                    this.AppendTxt(string.Format("当前要订购的业务代码是：{0}", this.cbbCommonService.SelectedValue));
                    document.InvokeScript("bookIncrementProduct", args);
                }
                else
                {
                    this.AppendTxt("没有找到对应的页面," + this.urlProductOrder);
                }
            }
        }

        private void QueryState(string phone)
        {
            HtmlDocument document = WebBrowserHelper.getDocFromWebBrowser(this.wbMain, this.urlProductOrder);
            if (document != null)
            {
                object[] args = new object[] { phone };
                document.InvokeScript("b", args);
            }
        }

        private void readDBTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                this.readDBTimer.Stop();
                DataSet set = SqliteManager.ExecuteDataSet(string.Format("select * from phonelist where state='{0}' limit 1 offset 0", SqliteManager.NOTBEGIN));
                if ((set != null) && (set.Tables[0].Rows.Count > 0))
                {
                    for (int i = 0; i < set.Tables[0].Rows.Count; i++)
                    {
                        DataRow row = set.Tables[0].Rows[i];
                        string phone = row["phone"].ToString();
                        this.QueryState(phone);
                        SqliteManager.ExecuteNonQuery(string.Format("update phonelist set state='{0}' where phone='{1}'", SqliteManager.QUERYING, phone));
                        Random random = new Random();
                        this.Sleep(random.Next(0x3e8, 0x1388));
                    }
                }
            }
            catch (Exception exception)
            {
                this.AppendTxt(exception.Message);
            }
            finally
            {
                this.readDBTimer.Start();
            }
        }

        private void ReayNext()
        {
            if (this.running)
            {
                int num;
                int num2;
                int num3;
                if (this.serviceType == -1)
                {
                    num = Convert.ToInt32(this.tbStart.Text.Trim());
                    num2 = Convert.ToInt32(this.tbEnd.Text.Trim());
                    Random random = new Random();
                    if (num2 <= 0)
                    {
                        this.Main086();
                        this.AppendTxt(string.Format("等待0秒后继续执行", new object[0]));
                    }
                    else
                    {
                        num3 = random.Next(num, num2);
                        this.AppendTxt(string.Format("等待{0}秒后继续执行", num3));
                        this.tProduct.Interval = num3 * 0x3e8;
                        this.tProduct.Start();
                    }
                }
                else
                {
                    num = Convert.ToInt32(this.tbStart.Text.Trim());
                    num2 = Convert.ToInt32(this.tbEnd.Text.Trim());
                    num3 = 0;
                    if (num2 <= 0)
                    {
                        this.MainCommon();
                        this.AppendTxt(string.Format("等待0秒后继续执行", new object[0]));
                    }
                    else
                    {
                        num3 = new Random().Next(num, num2);
                        this.tCommon.Interval = num3 * 0x3e8;
                        this.tCommon.Start();
                        this.AppendTxt(string.Format("等待{0}秒后继续执行", num3));
                    }
                }
            }
        }

        private void RegIMEI()
        {
            Random random = new Random();
            this.Sleep(random.Next(0xbb8, 0x2710));
            this.AppendTxt("准备注册 IMEI");
            HtmlDocument document = WebBrowserHelper.getDocFromWebBrowser(this.wbMain, this.urlMain);
            if (document != null)
            {
                object[] args = new object[] { this.curPhone, this.curIMEI };
                document.InvokeScript("c", args);
            }
            else
            {
                this.AppendTxt("子页面js 调用错误， 调用名称: c");
            }
        }

        private void Sleep(int milisencondsTimeout)
        {
            Thread thread = new Thread(delegate(object o)
            {
                Thread.Sleep(milisencondsTimeout);
            });
            thread.Start(this);
            while (thread.IsAlive)
            {
                Application.DoEvents();
            }
        }

        private void tCommon_Tick(object sender, EventArgs e)
        {
            this.tCommon.Stop();
            this.MainCommon();
        }

        private void tProduct_Tick(object sender, EventArgs e)
        {
            this.tProduct.Stop();
            this.Main086();
        }

        private void wbMain_BeforeNewWindow(object sender, WebBrowserExtendedNavigatingEventArgs e)
        {
            
        }

        private void wbMain_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            this.AppendTxt("打开url：" + e.Url.ToString());
            if (e.Url.ToString().IndexOf("ajaxIncrementProMarketingAction.action") > 0)
            {
                WebBrowser browser = (WebBrowser)sender;
                MessageBox.Show(browser.DocumentText);
            }
            if (e.Url.ToString().Contains(this.urlMain))
            {
                this.LoadLocalJS(this.urlMain);
            }
            if (this.running)
            {
                if (e.Url.ToString().Contains(this.urlProductOrder))
                {
                    this.LoadLocalJS(this.urlProductOrder);
                    this.ExcuteQueryInfo();
                }
                if (e.Url.ToString().Contains(this.urlRegUrl))
                {
                    this.LoadLocalJS(this.urlRegUrl);
                    this.RegIMEI();
                }
                if (e.Url.ToString().Contains(this.urlBookProductResult))
                {
                    this.ProcBookProInfo();
                }
            }
        }
    }
}
